init 关键字 |
您所在的位置:网站首页 › init channeltype fail › init 关键字 |
init(C# 参考)
项目
04/07/2023
在 C# 9 及更高版本中,init 关键字在属性或索引器中定义访问器方法。 init-only 资源库仅在对象构造期间为属性或索引器元素赋值。 这会强制实施不可变性,因此,一旦初始化对象,将无法再更改。 有关详细信息和示例,请参阅属性、自动实现的属性和索引器。 以下示例为名为 YearOfBirth 的属性同时定义 get 和 init 访问器。 它使用名为 _yearOfBirth 的私有字段备份属性值。 class Person_InitExample { private int _yearOfBirth; public int YearOfBirth { get { return _yearOfBirth; } init { _yearOfBirth = value; } } }通常,init 访问器包含分配一个值的单个语句,如前面的示例所示。 请注意,由于 init,以下操作将不起作用: var john = new Person_InitExample { YearOfBirth = 1984 }; john.YearOfBirth = 1926; //Not allowed, as its value can only be set once in the constructorinit 访问器可用作表达式主体成员。 例如: class Person_InitExampleExpressionBodied { private int _yearOfBirth; public int YearOfBirth { get => _yearOfBirth; init => _yearOfBirth = value; } }init 访问器还可以在自动实现的属性中使用,如以下示例代码所示: class Person_InitExampleAutoProperty { public int YearOfBirth { get; init; } } C# 语言规范有关详细信息,请参阅 C# 语言规范。 该语言规范是 C# 语法和用法的权威资料。 请参阅 C# 参考 C# 编程指南 C# 关键字 属性 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |